# encoding=utf8
from docx import Document
from docx.shared import Pt

import qrcode
import requests
import os

down_path = "D:\\小丸子抖音爬虫视频\\"
headers = {
	"User-Agent": "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Mobile Safari/537.36"
}
total_cursor = 7		# 一共75集，偏移了7页
per_count = 10		# 每页10集
short_url = "https://v.douyin.com/e4BxGEn/"		# 合集短连接地址
prefix_url = "https://www.iesdouyin.com/web/api/mix/item/list/?mix_id="		# 【Requests URL】-前面部分
suffix_url = "&count={}".format(per_count) + "&cursor={}"		# 【Requests URL】-后面部分
main_url = requests.get(url=short_url, headers=headers).url		# 获取合集地址栏url
mix_id = main_url.split("/")[6]		# 获取该合集的id
qrcode_path = "D:\\小丸子抖音爬虫视频\\img\\"
doc_abs_path = "D:\\小丸子抖音爬虫视频\\img\\"
doc_name = "111.docx"
video_list = []

if not os.path.exists(down_path):
	os.mkdir(down_path)
for cursor in range(total_cursor + 1):
	page_url = prefix_url + mix_id + suffix_url.format(cursor * 10)		# 页面url
	page_json = requests.get(page_url).json()
	page_count = len(page_json["aweme_list"])		# 每个url.json()包含的视频数量
	for count in range(page_count):
		video_url = page_json["aweme_list"][count]["video"]["play_addr"]["url_list"][0]
		episodes = cursor * 10 + count + 1		# 集数
		str_episodes = "第" + str(episodes) + "集："
		video_list.append((str_episodes, video_url))
		print(str_episodes + "   " + video_url)

doc = Document(doc_abs_path + doc_name)
for strep, video in video_list:
	filename = strep
	qr = qrcode.QRCode(
		version=5,
		error_correction=qrcode.constants.ERROR_CORRECT_L,
		box_size=10,
		border=4,
	)
	qr.add_data(video)
	qr.make(fit=True)
	img = qr.make_image()
	img.save(qrcode_path + filename)
	doc.add_paragraph(filename)
	doc.add_picture(qrcode_path + filename, width=Pt(300))
doc.save(doc_abs_path + "new" + doc_name)

